package com.maxd.service.message;

import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.MessageInfo;
import com.maxd.respository.message.MessageJpaRepository;
import com.maxd.respository.message.MessageRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 公告消息的service实现类
 */
@Service
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageJpaRepository userJpaRepository;
    @Autowired
    private MessageRepository userRepository;
    @Override
    public Result findAll() {
        return ResultUtil.success(userJpaRepository.findAll());
    }

    @Override
    public Result saveBody(MessageInfo messageInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        messageInfo.setCreateAt(sdf.format(now));
        return ResultUtil.success(userJpaRepository.save(messageInfo));
    }

    @Override
    public Result findOne(long id) {
        return ResultUtil.success(userJpaRepository.findById(id).orElse(null));
    }

    @Override
    public MessageInfo selectById(long id) {
        return userJpaRepository.findById(id).orElse(null);
    }

    @Override
    public Result delete(long id) {
        userJpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    @Override
    public Result find(String state,Pageable pageable) {
        return ResultUtil.success(userRepository.find(state,pageable));
    }

    @Override
    @Transactional
    public Result updateBody(MessageInfo userInfo) {
        MessageInfo foodBanner1 = userJpaRepository.findById(userInfo.getId()).orElse(null);
        assert foodBanner1 != null;
        BeanUtils.copyProperties(userInfo, foodBanner1);
        return ResultUtil.success();
    }

    @Override
    public Result findType(Integer type, Pageable pageable) {
        return ResultUtil.success(userRepository.findType(type,pageable));
    }

    @Override
    @Transactional
    public Result updateState(String state, String id) {
        Integer adminInfo = userRepository.updateState(state, Long.parseLong(id));
        if (adminInfo == 1) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ExceptionEnum.STATE_PWD_ERROR);
        }
    }

    @Override
    @Transactional
    public Result updateSendState(String state, String id) {
        Integer adminInfo = userRepository.updateSendState(state, Long.parseLong(id));
        if (adminInfo == 1) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ExceptionEnum.STATE_PWD_ERROR);
        }
    }


}
